<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * 自定义token认证
 */
class UserToken {
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next) {
        $token = $request->header("Authorization");
        if (empty($token)) {
            return response()->json(['code' => 1001, 'msg' => '登录凭证失效，请重新登录1']);
        } else if (is_array($token)) {
            $token = $token[0];
        }
        try {
            //具体根据实际情况修改
            $res = payload_decrypt();
            if ($res&&isset($res['user_id'])) {
//                if(intval($res['timestamp'])<(time()-86400*7)){//验证token有效期，
//                    return response()->json(['code' => 1001, 'msg' => '登录凭证失效，请重新登录2']);
//                }
                //验证单点登录 , 不需要可以注释
                $key=cache()->store('redis')->get("user_".$res['login_type']."_".$res['user_id']);
                if($key!==$token){
                    //  return response()->json(['code' => 1001, 'msg' => '登录凭证失效，请重新登录3']);
                }
                $request->payload = $res;
            } else {
                return response()->json(['code' => 1001, 'msg' => '登录凭证失效，请重新登录4','data'=>$res]);
            }
        } catch (\Exception $e) {
            return response()->json(['code' => 1001, 'msg' => '登录凭证失效，请重新登录5','data'=>$e->getMessage()]);
        }
        return $next($request);
    }
}
